/**
 * @copyright: Copyright (c) hotel.jd.com All Rights Reserved
 * @file: HttpClientUtil.java project: trip-hotel-resource
 * @creator: niehong1
 * @date: 2017/10/12
 */

package util;

import com.alibaba.fastjson.JSONObject;
import common.HttpResponseInfo;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;

/**
 * @description: HTTP调用工具类
 * @author: niehong1
 * @createdate: 2017-10-12 20:34
 * @lastdate:
 */
public class HttpClientUtil {
    /**
     * @description get请求调用
     * @author niehong1
     * @date 2017/10/12 20:33
     * @param url url地址
     * @return 请求响应报文
     * @throws IOException IOException
     * @throws URISyntaxException URISyntaxException
     */
    public static String get(String url) throws IOException, URISyntaxException {
        URL url1 = new URL(url);
        URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
        //得到浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //指定请求方式
        HttpGet get = new HttpGet(uri);
        String retStr = "";
        //执行请求
        CloseableHttpResponse response = httpclient.execute(get);
        try {
            int code = response.getStatusLine().getStatusCode();
            //判断请求是否成功
            if (code == HttpStatus.SC_OK) {
                //获取返回的实体
                HttpEntity entity = response.getEntity();
                //获取返回的内容
                retStr = EntityUtils.toString(entity);
            }
        } finally {
            response.close();
        }

        return retStr;
    }

    /**
     * @description get请求调用
     * @author niehong1
     * @date 2017/10/12 20:33
     * @param url url地址
     * @param timeout 超时时间 单位毫秒
     * @return 请求响应报文
     * @throws IOException IOException
     * @throws URISyntaxException URISyntaxException
     */
    public static HttpResponseInfo getWithTimeout(String url, int timeout, Map<String, String> header) throws IOException, URISyntaxException {
//        URL url1 = new URL(url);
//        URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
//        System.out.println("开始请求url=" + url + ", header=" + JSONObject.toJSONString(header));
        //得到浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout)
                .setSocketTimeout(timeout).build();
        //指定请求方式
        HttpGet get = new HttpGet(url);
        get.setConfig(requestConfig);

        // 设置HTTP请求header
        if (header != null && header.size() > 0) {
            for(Map.Entry<String, String> entry: header.entrySet()) {
                get.setHeader(entry.getKey(), entry.getValue());
            }
        }

        HttpResponseInfo responseInfo = null;
        //执行请求
        CloseableHttpResponse response = httpclient.execute(get);
        try {
            responseInfo = convertHttpResponse(response);
        } finally {
            response.close();
        }
        return responseInfo;
    }

    public static String post(String url, String content, Map<String, String> header) throws IOException, URISyntaxException {
        URL url1 = new URL(url);
        URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
        //得到浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //指定请求方式
        HttpPost post = new HttpPost(uri);

        // 设置HTTP请求header
        if ( header != null ) {
            for(Map.Entry<String, String> entry: header.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }

        StringEntity reqEntity = new StringEntity(content,"utf-8");
        post.setEntity(reqEntity);
        String retStr = "";
        //执行请求
        CloseableHttpResponse response = httpclient.execute(post);
        try {
            int code = response.getStatusLine().getStatusCode();
            //判断请求是否成功
            if (code == HttpStatus.SC_OK) {
                //获取返回的实体
                HttpEntity entity = response.getEntity();
                //获取返回的内容
                retStr = EntityUtils.toString(entity);
            }
        } finally {
            response.close();
        }

        return retStr;
    }

    /**
     * @description 功能描述: 从指定url下载文件保存到某个位置
     * @param url   下载链接
     * @param savePathAndFileName 保存路径和文件名
     * @throws IOException IOException
     * @throws URISyntaxException URISyntaxException
     */
    public static void downLoadFile(String url, String savePathAndFileName) throws IOException, URISyntaxException {
        URL url1 = new URL(url);
        URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
        File file = new File(savePathAndFileName);
        //得到浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //指定请求方式
        HttpGet get = new HttpGet(uri);
        //执行请求
        CloseableHttpResponse response = httpclient.execute(get);
        try {
            int code = response.getStatusLine().getStatusCode();
            //判断请求是否成功
            if (code == HttpStatus.SC_OK) {
                //获取返回的实体
                HttpEntity entity = response.getEntity();
                FileUtils.writeByteArrayToFile(file, EntityUtils.toByteArray(entity));
            }
        } finally {
            response.close();
        }
    }

    /**
     * @description 功能描述: 解压文件
     * @param fileAddress  zip文件路径（路径格式如：C:\\Users\\45335\\Desktop\\testZip.zip）
     * @param unZipAddress //zip文件解压路径
     * @throws IOException IOException
     */
    public static String unzipFile(String fileAddress, String unZipAddress) throws IOException {
        return null;
    }

    /**
     * http响应转换
     * @param response
     * @return
     * @throws IOException
     */
    private static HttpResponseInfo convertHttpResponse(HttpResponse response) throws IOException {
        HttpResponseInfo responseInfo = new HttpResponseInfo();
        responseInfo.setCode(response.getStatusLine().getStatusCode());
        responseInfo.setResponseStr(EntityUtils.toString(response.getEntity(), "UTF-8"));
        responseInfo.setHeaders(response.getAllHeaders());
        return responseInfo;
    }
}
